package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1. 处理业务异常
        // 1.1.地址簿为空
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 1.2. 购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.listShoppingCart(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 2. 向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//支付状态
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        orders.setPhone(addressBook.getPhone());//用户手机号
        orders.setUserId(userId);//用户id
        orders.setUserName(addressBook.getConsignee());//用户姓名
        orders.setAddress(addressBook.getDetail());//用户地址
        orderMapper.insert(orders);//插入订单数据

        // 3. 向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        // 4. 清空购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        // 5. 封装VO返回数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 1. 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 2. 查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 3. 根据订单id更新订单数据
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1. 开发分页功能
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 2. 插入用户id
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);

        // 3. 执行分页查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        // 4. 查询出订单明细
        List<OrderVO> orderVOList = new ArrayList<>();
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {
                Long ordersId = orders.getId();

                // 4.1. 查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(ordersId);

                // 4.2. 封装Vo
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                // 4.3. 添加集合
                orderVOList.add(orderVO);
            }
        }
        // 5. 封装分页结果
        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailsById(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);

        // 2. 查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());

        // 3. 封装Vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrderById(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);
        // 1.1. 订单不存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 2. 订单状态校验 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 订单若是在待接单状态下时
        if (orders.getStatus() == 2) {
            // 3.1 需要退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 4. 更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetitionOrderById(Long id) {
        // 1. 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 2. 根据用户id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(id);

        // 3. 将订单详情转化为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 3.1. 将原订单详情里面的菜品信息重复复制到购物车对象当中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        // 4. 购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1. 开启分页功能
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 2. 执行分页查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        // 3. 封装订单信息
        List<Orders> ordersList = ordersPage.getResult();
        // 3.1. 部分订单状态，需要额外返回订单菜品信息
        List<OrderVO> orderVOList = new ArrayList<>();
        // 3.2. 订单状态校验
        if (!CollectionUtils.isEmpty(ordersList)) {

            // 4. 查询订单菜品详细信息
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());
                // 4.1. 将每一条订单菜品信息拼接为字符串（宫保鸡丁*3；）
                List<String> orderDishList = orderDetailList.stream().map(x -> {
                    String orderDish = x.getName() + "*" + x.getNumber();
                    return orderDish;
                }).collect(Collectors.toList());
                // 4.2. 将该订单对应的所有菜品信息拼接为字符串（宫保鸡丁*3；回锅肉*2）
                String join = String.join("；", orderDishList);
                orderVO.setOrderDishes(join);
                orderVOList.add(orderVO);
            }
        }

        // 5. 封装分页结果
        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 1. 根据状态，分别查找
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);//待接单数量
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);//待派送数量
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);//派送中数量

        // 2. 封装Vo
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        // 3. 返回结果
        return orderStatisticsVO;


    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orders.getId());

        // 2. 封装Vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        // 3. 返回结果
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersDTO
     */
    @Override
    public void confirm(OrdersDTO ordersDTO) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(ordersDTO.getId());

        // 2. 订单状态校验 不是待接单
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 更新订单状态
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());

        // 2. 订单状态查询
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 支付状态
        if (orders.getPayStatus() == Orders.PAID) {
            // 说明已支付，需退款
            throw new OrderBusinessException("商家退款中！！！");
        }

        // 4. 更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        // 5. 更新数据库
        orderMapper.update(orders);
    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());

        // 2. 支付状态
        if (orders.getPayStatus() == Orders.PAID) {
            // 2.1. 说明已支付，需退款
            throw new OrderBusinessException("商家退款中！！！");
        }

        // 3. 更新状态
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());

        // 4. 更新数据库
        orderMapper.update(orders);
    }

    /**
     * 订单配送
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);

        // 2. 订单状态校验
        if (orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 更新状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        // 4. 更新数据库
        orderMapper.update(orders);
    }

    /**
     * 订单完成
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);

        // 2. 订单状态校验
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3. 更新状态
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        // 4. 更新数据库
        orderMapper.update(orders);
    }

    @Override
    public void websocket() {
        // 1. 通过websocket向客户端游览器推送消息
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", 1);
        map.put("content", "订单已支付");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    @Override
    public void reminder(Long id) {
        // 1. 查询订单
        Orders orders = orderMapper.selectById(id);

        // 2. 订单校验
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 3. 调用WebSocketServer 向客户端游览器推送消息
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber() + "，请及时接单");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
